package kr.co.exight.onApp;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import library.ActionClass;
import library.HtmlProgressManager;
import library.Library;
import library.Library.DialogChoiceYes;
import library.Variables;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;
import struct.LibraryInfo;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

public class ActivityLibrary extends Activity implements OnClickListener {


	/** Called when the activity is first created. */
	ListView lstLibrary;
	ArrayList<LibraryInfo> arrLibraryInfo;
	TestAdapter adapter;
	HashMap hashMap;
	HtmlProgressManager htmlProgress;

	public static int selectedPlace = 0;
	public static final int CENTRAL_NO = 1;
	public static final int HAKSUL_NO = 2;

	ToggleButton btnCentral, btnHaksul;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);


		setContentView(R.layout.act_library);
		selectedPlace = CENTRAL_NO;

		lstLibrary = (ListView)findViewById(R.id.library_lstLibrary);
		
		btnCentral = (ToggleButton)findViewById(R.id.library_btnLeft);
		btnHaksul = (ToggleButton)findViewById(R.id.library_btnRight);
		Button btnReload = (Button)findViewById(R.id.library_btnReload);
		
		btnCentral.setOnClickListener(this);
		btnHaksul.setOnClickListener(this);
		btnReload.setOnClickListener(this);
		
		loadDataFromWeb(Variables.YONSEI_LIBRARY_URL);
		
		
	}

	// load URL

	public void loadDataFromWeb(String destUrl){
		showDialog(0);
		htmlProgress = new HtmlProgressManager(new ActionClass(this) {
			@Override
			public Object doParse(String url) {
				// TODO Auto-generated method stub

				Source source = null;
				try {
					source = new Source(new URL(url));
				} catch (MalformedURLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				source.fullSequentialParse();

				List trList = source.getAllElements(HTMLElementName.TR);

				HashMap<String, ArrayList<LibraryInfo>> hash = new HashMap<String, ArrayList<LibraryInfo>>();

				ArrayList<LibraryInfo> arrHaksul = new ArrayList<LibraryInfo>();
				ArrayList<LibraryInfo> arrCentral = new ArrayList<LibraryInfo>();

				ArrayList<LibraryInfo> tmp = null;

				hash.put("학술정보관", arrHaksul);
				hash.put("중앙도서관", arrCentral);

				Iterator trIter = trList.iterator();

				trIter.next();
				trIter.next();

				String floorName = null;
				while(trIter.hasNext()){ // TR 안으로 들어감
					Element tr = (Element) trIter.next();

					List dataList = tr.getAllElements(HTMLElementName.TD);
					Iterator dataIter = dataList.iterator();

					int chk = 0;

					List resultList = new ArrayList();

					LibraryInfo a = new LibraryInfo();
					//원하는 결과 값이 들어가는 부분.

					while(dataIter.hasNext()){ // TD 안으로 들어간다
						Element data = (Element) dataIter.next();
						String value = 
								data.getContent().getTextExtractor().toString();

						if(value.equals("학술정보원") ){
							tmp = arrHaksul;
							continue;
						}else if(value.equals("중앙도서관"))	{
							tmp = arrCentral;
							continue;
						}else if(value.equals("(예약하기)")) {
							continue;
						}else if(value.contains("층")){
							floorName = value;
							continue;
						}


						switch(chk){
						case 0:
							a.setFloor(floorName); // 층수 입력하기
							a.setRoomName(value); // 실(Room)명 입력하기
							chk++;
							break;
						case 1:
							a.setAllSeat(Integer.parseInt(value));
							chk++;	
							break;
						case 2:
							a.setUsingSeat(Integer.parseInt(value));
							chk++;	
							break;
						case 3:
							a.setAvailableSeat(Integer.parseInt(value));
							tmp.add(a);
							chk++;	
							break;
						}

					}

				}
				return hash;
			}// for


			@Override
			public void actionSuccess(Object object) {
				// TODO Auto-generated method stub
				try{
					dismissDialog(0);
				}catch(IllegalArgumentException e){
					e.printStackTrace();
				}
				hashMap = (HashMap)object;
				setViewMatched();
			}

			@Override
			public void actionFailed() {
				// TODO Auto-generated method stub
				try{
					dismissDialog(0);
				}catch(IllegalArgumentException e){
					e.printStackTrace();
				}
				
				Library.makeYesDialog(ActivityLibrary.this, "인터넷 연결이 좋지 않습니다.\n연결을 확인해주세요", "확인", new DialogChoiceYes() {

					public boolean choiceYes() {
						// TODO Auto-generated method stub
						onBackPressed();
						return false;
					}
				});
			}
		}, destUrl);
		htmlProgress.start();

	}



	public void setViewMatched(){
		if(selectedPlace == CENTRAL_NO){
			arrLibraryInfo = (ArrayList<LibraryInfo>)hashMap.get("중앙도서관");
		} else {
			arrLibraryInfo = (ArrayList<LibraryInfo>)hashMap.get("학술정보관");
		}

		if(adapter == null){
			adapter = new TestAdapter();
			lstLibrary.setAdapter(adapter);
		}else {
			adapter.notifyDataSetChanged();
		}
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		loadDataFromWeb(Variables.YONSEI_LIBRARY_URL);
		super.onResume();

	}





	@Override // 로딩바 안보이게 하기
	protected Dialog onCreateDialog(int id) {
		final Dialog dialog = new Dialog(this, R.style.Theme_Dialog);
		View view = getLayoutInflater().inflate(R.layout.dialog_progress, null);
		dialog.setContentView(view);
		dialog.setOnCancelListener(new OnCancelListener() {

			public void onCancel(DialogInterface dialog) {
				// TODO Auto-generated method stub
				finish();

			}

		});
		return dialog;
	}

	class TestAdapter extends BaseAdapter{

		public int getCount() {

			return arrLibraryInfo.size();
		}

		public Object getItem(int position) {

			return arrLibraryInfo.get(position);
		}

		public long getItemId(int position) {

			return 0;
		}

		public View getView(final int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if(v == null){
				v = getLayoutInflater().inflate(R.layout.cell_library, null);
			}

			TextView tvFloor = (TextView)v.findViewById(R.id.libraryCell_tvFloor);
			TextView tvName = (TextView)v.findViewById(R.id.libraryCell_tvName);
			TextView tvSeat = (TextView)v.findViewById(R.id.libraryCell_tvSeat);
			
			Library.setFontNanumGothic(tvFloor);
			Library.setFontNanumGothic(tvName);
			Library.setFontNanumGothic(tvSeat);
			
			Library.setTextViewBold(tvFloor);
			Library.setTextViewBold(tvName);
			Library.setTextViewBold(tvSeat);
			
			LibraryInfo a = arrLibraryInfo.get(position);

			if(a.getRoomName().contains("(예약하기)")) {
				a.setRoomName(a.getRoomName().substring(0, a.getRoomName().length()-6));
			}
			tvFloor.setText(a.getFloor());
			
			tvName.setText(a.getRoomName());
			tvSeat.setText(a.getAvailableSeat() +"/"+ a.getAllSeat());
			return v;
		}
	}

	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		
		case R.id.library_btnLeft:
			if(btnHaksul.isChecked()){
				btnHaksul.setChecked(false);
				btnCentral.setChecked(true);
				selectedPlace = CENTRAL_NO;
				setViewMatched();
			}else {
				btnCentral.setChecked(true);
			}
			
			break;
		case R.id.library_btnRight:
			if(btnCentral.isChecked()){
				btnCentral.setChecked(false);
				btnHaksul.setChecked(true);
				selectedPlace = HAKSUL_NO;
				setViewMatched();
			}else {
				btnHaksul.setChecked(true);
			}
			
			break;
		case R.id.library_btnReload:
			loadDataFromWeb(Variables.YONSEI_LIBRARY_URL);
			break;
		}
	}

}

